package com.zzh.netty.aio;

import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.AsynchronousServerSocketChannel;
import java.nio.channels.AsynchronousSocketChannel;
import java.nio.channels.CompletionHandler;

/**
 * @PackageName:com.zzh.netty.aio
 * @ClassName:AioServer
 * @Description:
 * @author:zhangzhanheng
 * @date: 2021/1/30 11:17
 */
public class AioServer {

    public static void main(String[] args) throws IOException, InterruptedException {
        final AsynchronousServerSocketChannel socketChannel =
                AsynchronousServerSocketChannel.open().bind(new InetSocketAddress(9000));
        socketChannel.accept(null, new CompletionHandler<AsynchronousSocketChannel, Object>() {
            @Override
            public void completed(AsynchronousSocketChannel result1, Object attachment) {
                try {
                    System.out.println("2--"+Thread.currentThread().getName());
                    //再此接收客户端连接，如果不写这行代码后面的客户端连接不上服务器
                    socketChannel.accept(attachment,this);
                    System.out.println(result1.getRemoteAddress());
                    ByteBuffer buffer = ByteBuffer.allocate(1024);
                    result1.read(buffer, buffer, new CompletionHandler<Integer, ByteBuffer>() {
                        @Override
                        public void completed(Integer result, ByteBuffer attachment) {
                            System.out.println("3---"+Thread.currentThread().getName());
                            attachment.flip();
                            System.out.println(new String(attachment.array(),0,result));
                            result1.write(ByteBuffer.wrap("HellpClient".getBytes()));
                        }

                        @Override
                        public void failed(Throwable exc, ByteBuffer attachment) {
                            exc.printStackTrace();
                        }
                    });
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }

            @Override
            public void failed(Throwable exc, Object attachment) {
                exc.printStackTrace();
            }
        });
        System.out.println("1----"+Thread.currentThread().getName());
        Thread.sleep(Integer.MAX_VALUE);
    }
}
